'use strict';

var jwt = require('jwt_common/node_modules/jwt-simple');
var secret = Buffer.from('fc651sd3fc1sd4b64d14d984', 'hex');
const tokenExp = 30 * 24 * 3600000 / 1000;

const db = uniCloud.database();
const collection = db.collection('user');
exports.main = async (event, context) => {
	var user = await collection.where({
		username: event.user,
		password: event.pwd
	}).get()
	if (user.affectedDocs < 1) {
		return {
			code: -2,
			msg: '账号或密码错误'
		}
	} else {
		var payload = {
			 user: event.user,
			 exp: Date.now() + tokenExp,
		};
		var token = jwt.encode(payload, secret);
		//console.log(token)
		return {
			username:event.user,
			token:token,
			code: 0,
			msg: '登录成功'
		}
	}
	
};